import { Schema } from 'mongoose';
import { IMessage } from '../types/IMessage';
import { ToolCallSchema } from './ToolCallSchema';

export const MessageSchema = new Schema<IMessage>({
  messageId: { type: String, required: true, unique: true, index: true },
  sessionId: { type: String, required: true, index: true },
  userId: { type: String, required: true, index: true },
  role: {
    type: String,
    enum: ['user', 'assistant', 'system', 'tool'],
    required: true,
    index: true
  },
  content: {
    text: { type: String, maxlength: 50000 },
    attachments: [{ type: Schema.Types.ObjectId, ref: 'Attachment' }],
    metadata: { type: Schema.Types.Mixed },
    // 工具调用
    toolCalls: [ToolCallSchema],
    toolCallId: { type: String, sparse: true },
    toolResult: {
      success: { type: Boolean },
      data: { type: Schema.Types.Mixed },
      error: {
        code: { type: String },
        message: { type: String },
        details: { type: Schema.Types.Mixed }
      },
      executionTime: { type: Number, min: 0 },
      resourceUsage: {
        memory: { type: Number, min: 0 },
        cpu: { type: Number, min: 0 },
        network: { type: Number, min: 0 }
      }
    }
  },
  messageType: {
    type: String,
    enum: ['text', 'file', 'image', 'command', 'system', 'tool_call', 'tool_result'],
    default: 'text',
    index: true
  },
  parentMessageId: { type: String, sparse: true, index: true },
  threadId: { type: String, sparse: true, index: true },
  tokens: {
    input: { type: Number, min: 0 },
    output: { type: Number, min: 0 },
    total: { type: Number, min: 0 }
  },
  processingTime: { type: Number, min: 0 },
  editedAt: { type: Date },
  deletedAt: { type: Date, sparse: true }
}, {
  timestamps: true,
  collection: 'messages'
});

// Compound Indexes
MessageSchema.index({ sessionId: 1, createdAt: 1 });
MessageSchema.index({ userId: 1, createdAt: -1 });
MessageSchema.index({ role: 1, messageType: 1 });
MessageSchema.index({ threadId: 1, createdAt: 1 }, { sparse: true });
MessageSchema.index({ 'content.text': 'text' });
